package edu.tsinghua.ddb.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.tsinghua.ddb.beans.Predicate;
import edu.tsinghua.ddb.dictionary.Column;
import edu.tsinghua.ddb.dictionary.GD;
import edu.tsinghua.ddb.dictionary.GlobalDictionary;
import edu.tsinghua.ddb.dictionary.Table;

/**
 * Wrapper of initiation ddb for script
 */
public class ScriptInterface {
	public Boolean createTable(String tableName, String[] columns) {
		List<Column> l = new ArrayList<Column>(columns.length);

		for (String string : columns) {
			String[] ss = string.split(" ");
			if (ss.length != 2)
				throw new Error("param illegal");
			l.add(new Column(ss[0], ss[1]));
		}

		return GD.getInstance().createTable(tableName, l);
	}

	public boolean dropTable(String tableName) {
		GD.clean(tableName);
		return GD.getInstance().dropTable(tableName);
	}

	public boolean vfrag(String tableName, String[][] map) {
		Map<Column, String> rules = new HashMap<Column, String>();
		GlobalDictionary gd = GD.getInstance();
		Table t = gd.getTable(tableName);
		for (String[] line : map) {
			if (line.length != 2)
				throw new Error("param illegal");
			String[] colms = line[0].split(" ");
			String siteName = line[1];
			for (String col : colms) {
				Column c = t.getColumn(col);
				if (c == null)
					throw new Error(col + " is not in table!");
				if (c.isPrimaryKey())
					rules.put(c, null);
				else {
					rules.put(c, siteName);
				}
			}
		}
		return gd.vFragTable(tableName, rules);
	}

	public boolean hfrag(String tableName, String[][] map) {
		Map<Predicate, String> rules = new HashMap<Predicate, String>();
		GlobalDictionary gd = GD.getInstance();
		for (String[] line : map) {
			if (line.length != 2)
				throw new Error("param illegal");
			rules.put(new Predicate(line[0]), line[1]);
		}
		return gd.hFragTable(tableName, rules);
	}

	public boolean makePrimaryKey(String tableName, String columnName) {
		GlobalDictionary gd = GD.getInstance();
		Table t = gd.getTable(tableName);
		if (t == null)
			throw new Error("table illegal");
		Column c = t.getColumn(columnName);
		if (c == null)
			throw new Error("column illegal");
		c.setPrimaryKey(true);
		return true;
	}
}
